package com.exam.action;

import java.io.File;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.exam.dao.GradeDao;
import com.exam.dao.StudentDao;
import com.exam.model.ExcelModel;
import com.exam.model.StudentModel;
import com.exam.util.ExcelExportUtils;
import com.exam.util.JXLImportUtils;
import com.opensymphony.xwork2.Action;


/**
 * 刘楠
 */
public class ExcelAction {

	private File aaa;
	
	
	public File getAaa() {
		return aaa;
	}

	public void setAaa(File aaa) {
		this.aaa = aaa;
	}


	/**
	 * 导出学生成绩
	 * description:
	 * datetime:2017年5月13日 下午12:29:26
	 * @throws Exception 
	 */
	public void  exportExcel() throws Exception{
		GradeDao gradeDao = new GradeDao();
		List<ExcelModel> gradeList = gradeDao.getGradeList();
		ExcelExportUtils<ExcelModel> excel = new ExcelExportUtils<ExcelModel>();
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/vnd.ms-excel");//设置响应格式
		response.setHeader("content-disposition", "attachment ;fileName="+URLEncoder.encode("学生成绩信息.xls","UTF-8"));
		OutputStream os = response.getOutputStream();
		excel.generateExcel("学生成绩表", "学生成绩详细信息", gradeList, os, "yyyy-MM-dd");
	}
	
	/**
	 * 下载导入模板
	 */
	public void downLoadTemplate() throws Exception{
		HttpServletRequest request = ServletActionContext.getRequest();
		@SuppressWarnings("deprecation")
		String realPath = request.getRealPath("/template/");
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/vnd.ms-excel");//设置响应格式
		response.setHeader("content-disposition", "attachment ;fileName="+URLEncoder.encode("学生信息导入.xls","UTF-8"));
		OutputStream os = response.getOutputStream();
		FileUtils.copyFile(new File(realPath,"template.xls"), os);
	}
	/**
	 * 导出学生信息
	 * description:
	 * datetime:2017年5月13日 下午2:12:42
	 * @throws Exception 
	 */
	public String  importExcel() throws Exception{
		List<StudentModel> student = JXLImportUtils.getStudent(aaa);
		StudentDao studentDao = new StudentDao();
		for (StudentModel studentModel : student) {
			studentDao.addOneStudent(studentModel);
		}
		
		return Action.SUCCESS;
	}
	

}
